<template>
  <div class="maingl">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="main_crumbs">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>导入分类</span>
          </div>
        </div>

        <div class="main_tree">
          <h3 class="main_tree_h">菜单名称</h3>
          <div class="main_tree_b">
            <el-tree
              :data="list"
              show-checkbox
              node-key="id"
              ref="tree"
              v-loading="listLoading"
              element-loading-text="加载中"
              icon-class="el-icon-arrow-right"
              :default-checked-keys="defaultkeys"
              highlight-current
              default-expand-all
              @check-change="checkChange"
              @check="nodeChange"
              :props="defaultProps"
              style="min-height: 540px"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                  <el-link
                    type="danger"
                    @click="delet(data.id)"
                    v-if="data.company_id > 0"
                    >删除</el-link
                  >
                </span>
              </span>
            </el-tree>
          </div>
        </div>

        <div class="newConBox_p100 paddingBottom10" id="newConBox">
          <div class="newConBox_h32">
            <div :class="['newConBox ', { on: searchBarFixed }]">
              <el-button type="primary" @click="Grant" v-repeatClick
                >确认导入</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  category_list,
  category_use,
  category_dieDelete,
  category_deleteBefore,
} from "@/api/commodity/commodityClassification";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

export default {
  components: {},
  data() {
    return {
      // 列表数据
      list: [],
      listLoading: false,
      // 树型tree
      defaultkeys: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
      },
      // 监听滚动
      searchBarFixed: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 200
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 监听勾选
    checkChange(row, rows, rowu) {
      let key = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys());
      this.list.map((m) => {
        m.isSelect = false;
        if (m.selfNext.length != 0) {
          this.listNext(m.selfNext);
        }
      });
      key.forEach((e) => {
        this.list.map((p) => {
          if (e == p.id) {
            p.isSelect = true;
            return;
          } else {
            if (p.selfNext.length != 0) {
              this.keyNext(p.selfNext, e);
            }
          }
        });
      });
    },
    nodeChange(row, rows, rowu) {
      let id = row.id;
      let isSelect = row.isSelect;
      console.log(this.defaultkeys);
      if (!isSelect) {
        this.category_deleteBefore(id).then((res) => {
          if (res.errcode == 0) {
          } else {
            let msg = res.errmsg;
            this.$confirm(msg + ", 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "error",
            })
              .then(() => {})
              .catch(() => {
                this.$refs.tree.setChecked(id, true, true);
              });
          }
        });
      }
    },
    listNext(arry) {
      arry.map((m) => {
        m.isSelect = false;
        if (m.selfNext.length != 0) {
          this.listNext(m.selfNext);
        }
      });
    },
    keyNext(self, e) {
      self.map((p) => {
        if (e == p.id) {
          p.isSelect = true;
          return;
        } else {
          if (p.selfNext.length != 0) {
            this.keyNext(p.selfNext, e);
          }
        }
      });
    },
    nodecheck(data) {
      console.log(data);
    },
    // 删除
    delet(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      this.$confirm("是否删除分类?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.category_deleteBefore(id)
            .then((res) => {
              if (res.errcode == 0) {
                this.category_dieDelete(id);
              } else {
                let msg = res.errmsg;
                this.$confirm(msg + ", 是否继续?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "error",
                })
                  .then(() => {
                    this.category_dieDelete(id);
                  })
                  .catch(() => {});
              }
            })
            .catch((error) => {});
        })
        .catch(() => {});
    },
    // 删除前查询
    category_deleteBefore(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      return new Promise((resolve, reject) => {
        category_deleteBefore(data)
          .then((res) => {
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 彻底删除
    category_dieDelete(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      category_dieDelete(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.category_list();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 确认授权
    Grant() {
      let arry = [];
      this.list.map((w) => {
        if (w.isSelect) {
          arry.push({
            id: w.id,
            selfNext: [],
            title: w.title,
            company_id: w.company_id,
          });
          if (w.selfNext.length != 0) {
            this.catNext(w.selfNext, arry, arry[arry.length - 1]);
          }
        }
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          category_ids: JSON.stringify(arry),
        }
      );
      category_use(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "导入成功",
            type: "success",
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    catNext(self, arry, selfNext) {
      self.map((w) => {
        if (w.isSelect) {
          selfNext["selfNext"].push({
            id: w.id,
            selfNext: [],
            title: w.title,
            company_id: w.company_id,
          });
          if (w.selfNext.length != 0) {
            let xh = selfNext["selfNext"][selfNext["selfNext"].length - 1];
            this.catNext(w.selfNext, arry, xh);
          }
        }
      });
    },
    // 菜单列表
    category_list() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      category_list(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          let arry = [];
          res.data.category.map((e) => {
            if (e.isSelect) {
              if (e.selfNext.length != 0) {
                this.selfNext(e.selfNext, arry);
              } else {
                arry.push(e.id);
              }
            }
          });
          this.defaultkeys = arry;
          this.list = res.data.category;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    selfNext(self, arry) {
      self.map((e) => {
        if (e.isSelect) {
          if (e.selfNext.length != 0) {
            this.selfNext(e.selfNext, arry);
          } else {
            arry.push(e.id);
          }
        }
      });
    },
  },
  created() {
    // 菜单列表
    this.category_list();
  },
};
</script>
<style lang="scss" scoped>
.maingl {
  .main_table {
    margin-top: 20px;
    /deep/.el-table--border th:first-child .cell {
      padding-left: 70px;
    }
    /deep/.el-table--border td:first-child .cell {
      padding-left: 60px;
    }
    .maingl_ch {
      display: inline-block;
      margin-left: 10px;
      /deep/.el-checkbox__label {
        padding-left: 10px;
      }
    }
  }
  .newConBox.on {
    margin-left: -10px;
    padding-left: 10px;
  }
}
</style>
